package grape.attend.service.group.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import grape.attend.service.classe.api.IClasseService;
import grape.attend.service.classe.po.Classe;
import grape.attend.service.group.api.IGroupClasseRelService;
import grape.attend.service.group.po.Group;
import grape.attend.service.group.po.GroupUserRel;
import grape.attend.service.group.mapper.GroupUserRelMapper;
import grape.attend.service.group.api.IGroupUserRelService;
import grape.attend.service.user.dto.GroupAndClassesDto;
import grape.base.rest.client.user.UserClient;
import grape.base.service.user.api.IUserService;
import grape.base.service.user.po.User;
import grape.common.exception.runtime.RBaseException;
import grape.common.service.common.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 考勤组与用户关系表，一对多 服务实现类
 * </p>
 *
 * @author yangwei
 * @since 2020-05-08
 */
@Service
public class GroupUserRelServiceImpl extends BaseServiceImpl<GroupUserRelMapper, GroupUserRel> implements IGroupUserRelService {

    @Autowired
    @Lazy
    private IGroupClasseRelService iGroupClasseRelService;
    @Autowired
    private UserClient userClient;
    @Override
    public void checkClasse(List<String> userIds) {
        for (String userId : userIds) {
            List<GroupAndClassesDto> groupAndClassesDtos = iGroupClasseRelService.getGroupAndClassesCurrentByUserId(userId);
            List<Classe> classes = new ArrayList<>();
            if (!isEmpty(groupAndClassesDtos)) {
                for (GroupAndClassesDto groupAndClassesDto : groupAndClassesDtos) {
                    classes.addAll(groupAndClassesDto.getClasses());
                }
                List<Classe> crossTime = IClasseService.isCrossTime(classes);
                if (!isEmpty(crossTime)) {
                    User user = userClient.getUserById(userId);
                    throw new RBaseException(StrUtil.format("用户 {} 中的班次 {} 和 {} 时间有交集",user.getNickname(),crossTime.get(0).getName(),crossTime.get(1).getName()));
                }
            }
        }
    }
}
